﻿using FDSQLAssistant.Models;

namespace FDSQLAssistant.Repositories
{
    public class CommonRepository : ContextRepository, ICommonRepository
    {
        public DbType DbType() => Models.DbType.SqlServer;

        public TableInfo GetTableInfo(string tableName)
        {
            //           var sql =
            //               @"SELECT c.name,t.name AS Type,c.max_length AS Length FROM sys.columns AS c INNER JOIN sys.types AS t ON c.system_type_id=t.system_type_id
            //WHERE object_id=OBJECT_ID(@tableName)";
            var sql =
                @"SELECT c.name,t.name AS Type,c.max_length AS Length,is_identity IsIdentity,IsPk=CONVERT(BIT,CASE WHEN EXISTS (SELECT TOP 1 1 FROM sys.objects WHERE type='PK' AND parent_object_id=o.object_id AND name IN (SELECT name FROM sys.sysindexes WHERE indid IN (SELECT indid FROM sys.sysindexkeys WHERE id=c.object_id AND colid=c.column_id))) THEN 1 ELSE 0 END) FROM sys.columns AS c INNER JOIN sys.types AS t ON  t.user_type_id=c.user_type_id
INNER JOIN sys.objects AS o ON o.object_id=c.object_id
 WHERE o.object_id=OBJECT_ID(@tableName)";
            var columns = Query<ColumnInfo>(sql, new { tableName });
            return new TableInfo
            {
                Name = tableName,
                ColumnInfos = columns
            };
        }

        public CommonRepository(Config config) : base(config)
        {
        }
    }
}
